<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;

class Index extends Common
{
    public function index()
    {
//        halt(123);die();
//        获得所有的分类数据，往首页循环
        $fenlei = db('cate')->select();
//        dump($fenlei);die;
//        首页随机抽取三篇文章做循环展示
//        $article = db('article')->where('cate_id=1')->select();
        $article = $this->getNewsRandom(5);
//        dump($data);die;

//        dump($article);
        $hotarticle = db('article')->order('click desc')->limit(5)->select();
        $this->assign(array(
            'article'=>$article,
            'hotarticle'=>$hotarticle
        ));
        return view();
    }

    //    随机取数据
    public function getNewsRandom($num){
        $newslist = Cache::get('article');   //自己定义一个cache_key
        if(empty($newslist)){
            $newslist = Db::name('article')->where([])->cache('article',3600)->select();
        }
        $random_keys = array_rand($newslist,$num);
        foreach($random_keys as $key=>$value){
            $data[] = $newslist[$value];
        }
        return $data;
    }
}
